package main

import (
	"fmt"
	"os/exec"
	"sync"
)

func Cmd(cmd string, shell bool) []byte {
	if shell {
		out, err := exec.Command("bash", "-c", cmd).Output()
		if err != nil {
			panic("some error found")
		}
		return out
	} else {
		out, err := exec.Command(cmd).Output()
		if err != nil {
			panic("some error found")
		}
		return out
	}
}
func Collector(n *sync.WaitGroup) map[string]string {
	result := make(map[string]string)
	threadCountCmd := "ps -eLf|wc -l"
	result["thread_count"] = string(Cmd(threadCountCmd, true))

	systemUpTimeCmd := "date -d \"$(awk -F. '{print $1}' /proc/uptime) second ago\" +\"%Y-%m-%d %H:%M:%S\""
	result["system_uptime"] = string(Cmd(systemUpTimeCmd, true))
	mountStatusCmd := "df ~ -h"
	result["mount_status"] = string(Cmd(mountStatusCmd, true))

	networkEstablishedCmd := "netstat -n | awk '/^tcp(.+)ESTABLISHED/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	result["network_established_count"] = string(Cmd(networkEstablishedCmd, true))
	networkListenCmd := "netstat -an | awk '/^tcp(.+)LISTEN/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	result["network_listen_count"] = string(Cmd(networkListenCmd, true))

	networkTimeWaitCmd := "netstat -an | awk '/^tcp(.+)TIME_WAIT/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	result["network_time_wait_count"] = string(Cmd(networkTimeWaitCmd, true))
	networkLastAckCmd := "netstat -an | awk '/^tcp(.+)LAST_ACK/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	result["network_last_ack_count"] = string(Cmd(networkLastAckCmd, true))
	networkSynRecvCmd := "netstat -an | awk '/^tcp(.+)SYN_RECV/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	result["network_syn_recv_count"] = string(Cmd(networkSynRecvCmd, true))
	networkSynSentCmd := "netstat -an | awk '/^tcp(.+)SYN_SENT/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	result["network_syn_sent_count"] = string(Cmd(networkSynSentCmd, true))

	networkFinWait1Cmd := "netstat -an | awk '/^tcp(.+)FIN_WAIT1/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	result["network_fin_wait1_count"] = string(Cmd(networkFinWait1Cmd, true))
	networkFinWait2Cmd := "netstat -an | awk '/^tcp(.+)FIN_WAIT2/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	result["network_fin_wait2_count"] = string(Cmd(networkFinWait2Cmd, true))

	networkClosingConnCmd := "netstat -an | awk '/^tcp(.+)CLOSING/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	result["network_closing_conn_count"] = string(Cmd(networkClosingConnCmd, true))
	networkClosingStatusCmd := "netstat -an | awk '/^tcp(.+)CLOSED/ {++S[$NF]} END {for(a in S) print a, S[a]}'"
	result["network_closing_status_count"] = string(Cmd(networkClosingStatusCmd, true))
	fmt.Println(result)
	defer n.Done()
	return result
}

func main() {
	var go_sync sync.WaitGroup
	for i := 0; i < 4; i++ {
		go_sync.Add(1)
		go Collector(&go_sync)
	}
	go_sync.Wait()
}
